import requests
import threading
import os
import re
import time
from selenium import webdriver

from Crypto.Cipher import AES



head = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"}


mypath = os.path.dirname(os.path.abspath(__file__))


class mylistrun():
    rund = 0


class selenuim():
    def __init__(self):
        pen = webdriver.ChromeOptions()
        pen.binary_location = r"G:\Program Files (x86)\Application\chrome.exe"
        self.driver = webdriver.Chrome(chrome_options=pen)
        self.driver.implicitly_wait(120)

    def get(self,uur):
        gq_xpath = '//*[@id="playleft"]/iframe[2]'
        bd_xpath = '//*[@id="Player"]'
        self.driver.get(uur)
        time.sleep(1)
        src = self.driver.find_element_by_xpath(gq_xpath)
        ur = src.get_attribute("src").split("=")
        print("m3u8:",ur)
        return ur[1]

    def close(self):
        self.driver.quit()


def my_get(code):
    uur = code[0]
    path = code[1]
    if not os.path.exists(path):
        os.mkdir(path)
    ret = requests.get(uur,headers=head)
    print("解析m3u8",ret.text)
    code = ret.text.split("\n")[2]
    uur = uur.split(code.split("/")[1])[0]
    uur = uur + code[1:]
    m3u8(uur,path)


class mythr(threading.Thread):
    def __init__(self,mydef,code):
        threading.Thread.__init__(self)
        self.mydef = mydef
        self.code = code

    def run(self):
        self.mydef(self.code)
        mylistrun.rund -= 1


def m3u8(url,path):
    rs = requests.get(url,headers=head).text
    list_content = rs.split('\n')
    player_list = []
    key = ''
    for index,line in enumerate(list_content):
        if "#EXT-X-KEY" in line:
            method_pos = line.find("METHOD")
            comma_pos = line.find(",")
            method = line[method_pos:comma_pos].split('=')[1]
            uri_pos = line.find("URI")
            quotation_mark_pos = line.rfind('"')
            key_url = line[uri_pos:quotation_mark_pos].split('"')[1]
            res = requests.get(key_url)
            key = res.content
            print("Decode Method: ", method)
            print("key: ", key)
        elif 'http' in line:
            player_list.append(line)
    if(len(key)):
        cryptor = AES.new(key, AES.MODE_CBC, key)
    else:
        cryptor = None
    file_list = os.listdir(path)
    try:
        mysum = [int(i.split(".")[0]) if '.ts' in i else 0 for i in file_list]
    except:
        mysum = []
    for i,j in enumerate(player_list):
        print(j)
        if i+1 not in mysum:
            my_requests(cryptor,os.path.join(path,str(i+1) + '.ts'),j)
    print('下载完成',url)


def he(name):
    path = os.path.join(mypath,name)
    file_list = os.listdir(path)
    for u in file_list:
        m = os.listdir(os.path.join(path,u))
        max_ = max([int(i.split(".")[0]) for i in m])
        s = open(u + ".mp4","wb")
        for i in range(1,max_+1):
            with open(os.path.join(path,u,str(i) + '.ts'),"rb") as f:
                s.write(f.read())
        s.close()
        print('合成完毕',u)


def my_requests(cryptor,file_path,url):
    rs = re.search("//(.*?)/",url)
    data = {"Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,hmn;q=0.6",
        "Connection": "keep-alive",
        "Origin": "https://jx.jxbdzyw.com",
        "Referer": "https://jx.jxbdzyw.com/",
        "sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
        "sec-ch-ua-mobile": "?0",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "cross-site",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"}
    if rs:
        data.update({"Host":rs.groups()[0]})
    try:
        res = requests.get(url,headers=data)
        if res.status_code == 200:
            with open(file_path,'wb') as file:
                if cryptor:
                    file.write(cryptor.decrypt(res.content))
                else:
                    file.write(res.content)
            print('正在写入第{}'.format(file_path))
    except:
        pass


def dowin(url,name):
    my = selenuim()
    my_path = os.path.join(mypath,name)
    if not os.path.exists(my_path):
        os.mkdir(my_path)
    for i in range(1,22):
        while mylistrun.rund > 5:
            time.sleep(10)			
        myurl = url.format(i)
        print(myurl)
        url_ = my.get(myurl)
        mythr(my_get,(url_,os.path.join(my_path,str(i)))).start()
        mylistrun.rund += 1
    my.close()


if __name__ == "__main__":
    #dowin("http://www.kxxer.com/gresource/14031.html?14031-1-{}","精绝古城")
    he("精绝古城")

